/**
 * 
 */
package com.seguriapp.sync;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.seguriapp.communication.WebServiceConsumer;
import com.seguriapp.dao.CrimeCategoryDao;

/**
 * @author pjohnson
 * 
 */
public class CrimeCategoryTask extends AsyncTask<Object, String, String> {

	private Context mContext;

	public CrimeCategoryTask(final Context context) {
		mContext = context;
	}

	@Override
	protected String doInBackground(Object... arg0) {
		final WebServiceConsumer webServiceConsumer = WebServiceConsumer
				.getInstance(mContext);
		return webServiceConsumer.getCrimeCategories();
	}

	@Override
	protected void onPostExecute(final String result) {
		try {
			final JSONObject jSon = new JSONObject(result);
			mContext.getContentResolver().delete(CrimeCategoryDao.CONTENT_URI,
					null, null);
			JSONArray jSonCategories = jSon.optJSONArray("crimeCategoryList");
			if (jSonCategories == null) {
				jSonCategories = jSon.optJSONArray("entityTypeList");
			}
			for (int i = 0; i < jSonCategories.length(); i++) {
				mContext.getContentResolver().insert(
						CrimeCategoryDao.CONTENT_URI,
						CrimeCategoryDao.contentValuesToInsert(jSonCategories
								.getJSONObject(i)));
			}

		} catch (JSONException e) {
			Log.e("JSON Exception", e.getMessage());
		}
	}

}
